<template>
  <div>
    <van-cell
      :title="item"
      icon="search"
      v-for="(item, index) in suggestions"
      :key="index"
    >
      <div
        slot="title"
        v-html="highlight(item)"
        @click="$emit('search', item)"
      ></div>
    </van-cell>
    <!-- 通过{{}} -->
    <!-- <div>{{htnlStr}}</div> -->
    <!-- 通过 v-text -->
    <!-- <div v-text='htmlStr></div> -->
    <!-- 通过v-html -->
    <!-- <div v-html='htmlStr></div> -->
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
function debounce (fn, wait) {
  let timer = null
  return function (val) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.call(this, val)
    }, wait)
  }
}
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  components: {},
  data () {
    return {
      suggestions: [],
      timer: null
    }
  },
  created () {},
  mounted () {},
  methods: {
    highlight (str) {
      if (str) {
        return str.replace(new RegExp(this.searchText, 'gi'), '<span style="color:#3296fa">' + this.searchText + '</span>')
      }
    }
  },
  watch: {
    // 在对象当中定义方法
    // searchText: function () {}
    // searchText: () => {}
    // 侦听器基本写法
    // searchText (val) {
    //   console.log(val)
    // }
    searchText: {
      // handler (val) {
      //   if (this.timer) clearTimeout(this.timer)
      //   this.timer = setTimeout(async () => {
      //     const { data: { data: { options } } } = await
      //     getSearchSuggestions(val)
      //     this.suggestions = options
      //   }, 500)
      // },
      handler: debounce(async function (val) {
        const { data: { data: { options } } } = await
        getSearchSuggestions(val)
        this.suggestions = options
      }, 500),
      immediate: true
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>
</style>
